package com.hh.erp.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.hh.erp.interceptor.LoginInterceptor;
import com.hh.erp.interceptor.MyBatisInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;


/**
 * 系统配置需要什么 Bean 在这里去添加
 */
@Configuration
public class ApplicationBeanConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    /**
     * 添加拦截器进行登录验证
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**"); //拦截所有请求
    }

    /*
     * zhb 2022-07-20
     * 提供Mybatis 的拦截器，打印SQL,或者输出到日志文件
     */
    @Bean
    public Interceptor MyBatisInterceptor(){
        return new MyBatisInterceptor();
    }


    /**
     * Cors 允许跨域
     * @return
     */
    @Bean
    public CorsFilter corsFilters(){
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost");
        config.setAllowCredentials(true); // 是否运行session
        config.addAllowedMethod("*");  // GET,POS,PUT 方法都允许跨域
        config.addAllowedHeader("*"); // 允许哪些头部信息
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**",config);
        return new CorsFilter(configSource);
    }

    /**
     * 这个不用了，配置文件有会自动加载
     */
//    @Bean
//    @ConfigurationProperties(prefix = "spring.datasource")
//    public DataSource getMyDruidDataSource() {
//        //System.out.println("已注入自定义配置的spring.datasource数据源......");
//        return new DruidDataSource();
//    }
}